<template>
  <div class="container" v-loading="status_loading">
    <el-row>
      <el-form :model="formInline" label-width="120px" @keyup.enter.native="search">
        <el-col :span="6" align="left">
          <el-form-item :label="$t('m.out.waveordercode')">
            <el-input maxlength="20" show-word-limit v-model="formInline.waveordercode" placeholder></el-input>
          </el-form-item>
          <el-form-item :label="$t('m.out.storeordercode')">
            <el-input maxlength="20" show-word-limit v-model="formInline.storeordercode" placeholder></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" align="left">
          <el-form-item :label="$t('m.in.ordernumber')">
            <el-input maxlength="30" show-word-limit v-model="formInline.ordernumber"></el-input>
          </el-form-item>
          <el-form-item label="SKU">
            <el-input maxlength="20" show-word-limit v-model="formInline.sku"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" align="left">
          <el-form-item :label="$t('m.state')">
            <el-select v-model="formInline.stateid" :placeholder="$t('m.choose')">
              <el-option v-for="item in states" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="SupplierCode">
            <el-input maxlength="20" show-word-limit v-model="formInline.suppliercode" placeholder></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" align="left">
          <el-form-item :label="$t('m.pick.tasknumbercode')">
            <el-input maxlength="20" show-word-limit v-model="formInline.tasknumber" placeholder></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" align="right">
          <el-button type="primary" @click="search" v-if="hasPermission('search')">{{$t('m.query')}}</el-button>
          <el-button @click="sorting" v-if="hasPermission('sorting')">{{$t('m.out.sort')}}</el-button>
        </el-col>
      </el-form>
    </el-row>
    <div class="ellipse"></div>
    <el-table ref="table" stripe empty-text fits class="table-wrap single-select-table" :data="tableData" :row-style="tableRowStyle" :row-class-name="tableRowClassName" @row-click="rowClick" @selection-change="handleSingleSelectionChange" v-loading="tableLoading">
      <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
      <el-table-column align="center" prop="waveordercode" :label="$t('m.out.waveorder')">
        <template slot-scope="scope">
          <template v-if="hasPermission('table-waveorder')">
            <el-button @click.stop="getWaveorder(scope.row.waveorderid)" type="text">{{scope.row.waveordercode}}</el-button>
          </template>
          <template v-else>{{scope.row.waveordercode}}</template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('m.state')" align="center" prop="state">
        <!-- 1 待处理 2 待拣货 3 部分拣货 4 拣货完成 5 已取消  -->
        <!-- <template slot-scope="scope">
          <span v-if="scope.row.stateid==1">{{$t('m.quality.state1')}}</span>
          <span v-if="scope.row.stateid==2">{{$t('m.out.state2')}}</span>
          <span v-if="scope.row.stateid==3">{{$t('m.out.state6')}}</span>
          <span v-if="scope.row.stateid==4">{{$t('m.out.state7')}}</span>
          <span v-if="scope.row.stateid==5">{{$t('m.review.state2')}}</span>
        </template>-->
      </el-table-column>
      <el-table-column align="center" prop="pickingtask" :label="$t('m.out.pickingtask')"></el-table-column>
      <el-table-column align="center" prop="orderqty" :label="$t('m.out.orderqty')"></el-table-column>
      <el-table-column align="center" prop="totalqty" :label="$t('m.out.totalqty')"></el-table-column>
      <el-table-column align="center" prop="createdate" :label="$t('m.createdate')"></el-table-column>
    </el-table>

    <el-pagination background layout="sizes, prev, pager, next, jumper" :page-sizes="pageSizeList" :page-size="rowSize" :current-page="page" :total="totalRows" @current-change="currentChangeInitFn" @size-change="handleSizeChangeInitFn"></el-pagination>

    <!-- 二次分拣 dialog 开始 -->
    <el-dialog :close-on-click-modal="false" width="1200px" :title="$t('m.out.pickingtype2')" :visible.sync="dialogFormVisible" @close="closeSortForm">
      <el-form :model="formTaskid" ref="formTaskid" label-width="120px" @submit.native.prevent>
        <el-form-item :label="$t('m.tasknumber')" prop="taskid">
          <el-input maxlength="20" show-word-limit ref="number" @input="func" @blur="blur&&doSearchBlur()" @keyup.enter.native="doSearchEnter" v-model.trim="formTaskid.taskid" placeholder></el-input>
        </el-form-item>
        <el-form-item :label="$t('m.out.location')" prop="location">
          <el-input maxlength="20" show-word-limit ref="location" @input="funcSorting" @blur="blurSorting&&doSortingBlur()" @keyup.enter.native="doSortingEnter" v-model.trim="formTaskid.location" placeholder></el-input>
        </el-form-item>
      </el-form>
      <div v-loading="table_loading">
        <el-row :gutter="30" class="waveHead">
          <el-col :span="7" align="left" :offset="1">
            <b>{{$t('m.out.pickingtaskcode')}}:</b>
            <span>{{rowData[0].tasknumber}}</span>
          </el-col>
          <el-col :span="7" align="left">
            <b>{{$t('m.out.waveordercode')}}:</b>
            <span>{{sortForm.waveordercode}}</span>
          </el-col>
          <el-col :span="7" align="left">
            <b>{{$t('m.out.location')}}:</b>
            <span>{{rowData[0].tsareacode}}</span>
          </el-col>
        </el-row>
        <el-row class="waveHead" :gutter="30" style="margin-bottom:30px">
          <el-col :span="7" align="left" :offset="1">
            <b>{{$t('m.sorting.sortingstate')}}:</b>
            <span>{{rowData[0].state|stateFilterDetail(lan)}}</span>
            <!-- <span v-if="rowData[0].state==1">{{$t('m.out.state2')}}</span>
            <span v-if="rowData[0].state==2">{{$t('m.shelves.state5')}}</span>-->
          </el-col>
          <el-col :span="7" align="left">
            <b>{{$t('m.out.pickingusers')}}:</b>
            <span>{{sortForm.pickingusers}}</span>
          </el-col>
          <el-col :span="7" align="left">
            <b>{{$t('m.createdate')}}:</b>
            <span>{{sortForm.createdate}}</span>
          </el-col>
        </el-row>
        <el-table class="waveList" ref="waveTable" stripe :data="sortForm.sortDetialList" empty-text fits>
          <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
          <el-table-column align="center" :label="$t('m.out.pickingtaskcode')" prop="tasknumber"></el-table-column>
          <el-table-column align="center" label="SKU" prop="productspeccode"></el-table-column>
          <el-table-column align="center" label="SupplierCode" prop="suppliercode"></el-table-column>
          <el-table-column align="center" :label="$t('m.in.productname')" prop="productname"></el-table-column>
          <el-table-column align="center" :label="$t('m.in.productspec')" prop="productspec"></el-table-column>
          <el-table-column align="center" :label="$t('m.out.quantity')" prop="quantity"></el-table-column>
          <el-table-column align="center" :label="$t('m.page.location')" prop="locationcode"></el-table-column>
          <el-table-column align="center" :label="$t('m.sorting.sortingstate')">
            <template slot-scope="scope">{{scope.row.state|stateFilterDetail(lan)}}</template>
          </el-table-column>
        </el-table>
        <div class="btns">
          <el-button size="mini" @click="closeSortForm">{{$t('m.close')}}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 二次分拣 dialog 结束 -->
    <!-- 波次单 dialog 开始 -->
    <el-dialog width="1400px" :title="$t('m.out.waveorder')" :visible.sync="dialogFormVisible1">
      <el-row :gutter="30" class="waveHead">
        <el-col :span="8">
          <b>{{$t('m.out.waveordercode')}}:</b>
          <span>{{waveForm.waveordercode}}</span>
        </el-col>
        <el-col :span="8">
          <b>{{$t('m.state')}}:</b>
          <span>{{waveForm.state}}</span>
        </el-col>
        <el-col :span="8">
          <b>{{$t('m.createdate')}}:</b>
          <span>{{waveForm.createdate}}</span>
        </el-col>
      </el-row>
      <el-table empty-text fits class="waveTable" ref="waveTable" :span-method="objectSpanMethod" :data="table" :row-class-name="rowClassName">
        <el-table-column align="center" prop="__index" :label="$t('m.index')" width="50"></el-table-column>
        <el-table-column align="center" width="150" prop="ordercode" :label="$t('m.in.ordernumber')"></el-table-column>
        <el-table-column align="center" prop="tasknumber" label="TaskNmuber"></el-table-column>
        <el-table-column align="center" prop="sdstate" :label="$t('m.sorting.sortingstate')">
          <template slot-scope="scope">{{scope.row.sdstate|stateFilterDetail(lan)}}</template>
        </el-table-column>
        <el-table-column align="center" prop="ptdstate" :label="$t('m.sorting.pickingstate')">
          <template slot-scope="scope">{{scope.row.ptdstate|pickingStateFilter(lan)}}</template>
        </el-table-column>
        <el-table-column align="center" prop="productspeccode" label="SKU"></el-table-column>
        <el-table-column align="center" prop="suppliercode" label="SupplierCode"></el-table-column>
        <el-table-column align="center" prop="productname" :label="$t('m.in.productname')" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="productspec" :label="$t('m.in.productspec')" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="locationcode" :label="$t('m.page.location')"></el-table-column>
        <el-table-column align="center" prop="quantity" :label="$t('m.out.quantity')"></el-table-column>
        <el-table-column align="center" prop="stockoutquantity" :label="$t('m.pick.shortageqty')"></el-table-column>
        <el-table-column width="100" align="center" :label="$t('m.out.tsareaid')" prop="tsareacode"></el-table-column>
      </el-table>
      <div class="btns">
        <el-button size="mini" @click="close(waveForm)">{{$t('m.close')}}</el-button>
      </div>
    </el-dialog>
    <!-- 波次单 dialog 结束 -->
  </div>
</template>

<script>
import common from '@/utils/common'
export default {
  name:'Sorting',
  data(){
    return {
      taskid:null,
      blur:true, //判断是否触发blur事件
      blurSorting:false,
      show:false,
      tsarea:'',
      status_loading:false,
      table_loading:false,
      isSelect:false,
      formInline:{
        ordernumber:'',
        waveordercode:'',
        sku:'',
        stateid:null,
        storeordercode:'',
        suppliercode:null,
        tasknumber:''
      },
      table:[],
      tableData:[],
      dialogFormVisible:false,
      dialogFormVisible1:false,
      shop:[],
      warehouse:[],
      region:[],
      waveForm:{
        ordercode:'',
        waveordercode:'',
        waveorderid:null,
        value:''
      },
      sortForm:{},
      tarea:[],
      formTaskid:{
        taskid:null,
        location:''
      },
      rowData:[
        {
          pickingusers:'',
          createdate:'',
          locationcode:'',
          locationid:null,
          ordercode:'',
          orderid:null,
          pickingtaskdetailid:null,
          pickingtaskid:null,
          productid:null,
          productname:'',
          productspec:'',
          productspeccode:'',
          quantity:null,
          state:null,
          suppliercode:'',
          tasknumber:'',
          tsareacode:'',
          tsareaid:null
        }
      ]
    }
  },
  computed:{
    states(){
      return [
        {
          id:null,
          label:this.$t('m.all')
        },
        {
          id:1,
          label:this.$t('m.quality.state1')
        },
        {
          id:2,
          label:this.$t('m.out.state3')
        },
        {
          id:3,
          label:this.$t('m.sorting.state6')
        }
      ]
    }
  },
  filters:{
    //  1 待拣货，2 已完成
    stateFilter(val, lan){
      let result = ''
      switch (val){
      case 1:
        result = lan('m.quality.state1')
        break
      case 2:
        result = lan('m.out.finish')
        break
      }
      return result
    },
    // 拣货状态（1待拣货 3 缺货 9 已完成 10 已取消）
    pickingStateFilter(val, lan){
      let result = ''
      switch (val){
      case 1: result = lan('m.out.state2'); break
      case 3: result = lan('m.pick.state3'); break
      case 9: result = lan('m.pick.state9'); break
      case 20: result = lan('m.pick.state10'); break
      }
      return result
    },
    // 分拣状态 （ 1待二次分拣 2分拣完成 20已取消 ）
    stateFilterDetail(val, lan){
      let result = ''
      switch (val){
      case 1: result = lan('m.sorting.state1'); break
      case 2: result = lan('m.sorting.finish'); break
      case 20: result = lan('m.sorting.state20'); break
      }
      return result
    }
  },
  mounted(){

  },
  methods:{
    rowClassName({ row }){
      // if (row.tasknumber === this.submitForm.tasknumber){
      //   return 'warning-row'
      // }
      //通过每行的sdstate值判断，如果是2则已经完成，变绿色
      if (row.sdstate === 2){
        return 'success-row'
      }
      return ''
    },
    // 表格缩进
    objectSpanMethod({ rowIndex, columnIndex }){
      let MergeArr = [0, 1, 12]
      if (MergeArr.includes(columnIndex)){
        if (!this.getMergeRows.length){
          return {
            rowspan:1,
            colspan:1
          }
        } else {
          return {
            rowspan:this.getMergeRows[rowIndex],
            colspan:this.getMergeRows[rowIndex] ? 1 : 0
          }
        }
      }
    },
    init(){
      this.tableLoading = true
      this.$axios({
        method:'get',
        url:'/sorting/page',
        params:Object.assign({}, this.formInline, {
          page:this.page,
          rows:this.rowSize
        })
      }).then(({ data }) => {
        for (let i = 0;i < data.records.length;i++){
          data.records[i].createdate = common.timestampToTime(
            data.records[i].createdate
          )
          if (data.records[i].endsortingdata){
            data.records[i].endsortingdata = common.timestampToTime(
              data.records[i].endsortingdata
            )
          } else {
            data.records[i].endsortingdata = '- -'
          }
        }
        this.tableData = data.records
        this.totalRows = data.total
        setTimeout(()=>this.tableLoading=false,500)
      })
    },
    search(){
      this.page = 1
      this.init()
    },

    close(){
      this.dialogFormVisible1 = false
      this.init()
    },
    closeSortForm(){
      this.dialogFormVisible = false
      this.table_loading = false
      this.show = false
      this.$refs['formTaskid'].resetFields()
      this.sortForm = {}
      this.rowData = [
        {
          pickingusers:'',
          createdate:'',
          locationcode:'',
          locationid:null,
          ordercode:'',
          orderid:null,
          pickingtaskdetailid:null,
          pickingtaskid:null,
          productid:null,
          productname:'',
          productspec:'',
          productspeccode:'',
          quantity:null,
          state:null,
          suppliercode:'',
          tasknumber:'',
          tsareacode:'',
          tsareaid:null
        }
      ]
      this.init()
    },
    sorting(){
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.number.focus() //输入框默认获取焦点
      })
    },
    func(){
      //通过input事件改变blur的值，避免在enter之后blur事件不能被触发
      this.blur = true
    },
    funcSorting(){
      //通过input事件改变blur的值，避免在enter之后blur事件不能被触发
      this.blurSorting = true
    },
    doSearchBlur(){
      this.blur = true
      if (this.formTaskid.taskid){
        this.doSearch()
        this.$refs.location.focus()
      }
    },
    doSearchEnter(){
      this.blur = false
      this.$refs.number.select()
      if (this.formTaskid.taskid){
        this.doSearch()
        this.$refs.location.focus()
      }
    },
    doSearch(){
      this.table_loading = true
      this.sortForm = {}
      this.formTaskid.location = ''
      this.$axios({
        method:'get',
        url:`/sorting/tasknumber?tasknumber=${this.formTaskid.taskid}`
      }).then(({ data }) => {
        this.show = true
        data.createdate = common.timestampToTime(
          data.createdate
        )
        this.sortForm = data
        this.rowData = data.sortDetialList.filter(v => {
          return v.tasknumber === this.formTaskid.taskid
        })
        this.table_loading = false
        this.show = false
      }).catch(() => {
        this.table_loading = false
        this.show = false
      })
    },
    doSortingBlur(){
      this.blurSorting = true
      this.doSorting()
    },
    doSortingEnter(){
      this.blurSorting = false
      this.doSorting()
    },
    doSorting(){
      // 添加sortingid
      if (this.formTaskid.location){
        if (this.rowData[0].tsareacode === this.formTaskid.location){
          this.$axios({
            method:'put',
            url:`/sorting/dosort?tasknumber=${this.formTaskid.taskid}&sortingid=${this.sortForm.sortingid}`
          })
            .then(({ data }) => {
              //此单已全部分拣完成
              if (data.orderstate === 4){
                this.$message(this.$t('m.out.done'))
              }
              this.sortForm = data
              this.rowData = data.sortDetialList.filter(v => {
                return v.tasknumber === this.formTaskid.taskid
              })
              this.table_loading = false
            })
            .catch(() => {
              // 两个数据接口有关联性，从简处理了。
              this.table_loading = false
              this.show = false
            })
        } else {
          this.$message.error(this.$t('m.pick.match'))
        }
      }
    },
    getWaveorder(id){
      this.table=[]
      this
        .$axios({
          method:'get',
          url:`/sorting/getSortDetailByWaveOrderId?waveorderid=${id}`
        })
        .then(({ data }) => {
          data.createdate = common.timestampToTime(data.createdate)
          for (let i = 0;i < data.waveorderDetailOutput.length;i++){
            data.waveorderDetailOutput[i].tsareaid = null
          }
          this.waveForm = data
          let waveOrderList = this.cloneObject(this.waveForm.waveorderDetailOutput)
          // 格式化数据
          waveOrderList.map((item, index) => {
            item.waveorderdetailList.map((__item) => {
              this.table.push(Object.assign({}, __item, { __index:index + 1, ordercode:item.ordercode, tsareacode:item.tsareacode || '', tsareaid:item.tsareaid || '' }))
            })
          })
          let __index = 0
          let code = ''
          this.getMergeRows = []
          this.table.forEach((item, index) => {
            if (item.ordercode !== code){
              this.getMergeRows.push(1)
              code = item.ordercode
              __index = index
            } else {
              if (code){
                ++this.getMergeRows[__index]
                this.getMergeRows.push(0)
              }
            }
          })
          this.dialogFormVisible1 = true
        })
    },
    getTarea(){
      let that = this
      that.status_loading = true
      that
        .$axios({
          method:'get',
          url:'/tsarea/list'
        })
        .then(({ data }) => {
          that.tarea = data
          that.status_loading = false
        })
    },
    getArea(index, id){
      this.isSelect = true
      this.waveForm.waveorderDetailOutput[index].tsareacode = this.tarea.filter(
        function (item){
          return item.tsareaid === id
        }
      )[0].tsareacode
    },
    lan(arg){
      return this.$t(arg)
    }
  },
  activated(){
    this.init()
  },
  beforeRouteLeave(to, form, next){
    this.dialogFormVisible=false
    this.dialogFormVisible1=false
    next()
  }
}
</script>
<style lang="scss" scoped>
.el-form-item--mini span {
  font-size: 10px;
}
.el-select {
  width: 100%;
}
.mainTable {
  overflow-y: scroll;
}
.waveList.el-table p {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
.waveList.el-table .item,
.waveList.el-table .el-tooltip {
  padding: 5px 0;
}
.transition-box {
  position: fixed;
  z-index: 9;
  width: 250px;
  height: 120px;
  border-radius: 4px;
  background-color: #409eff;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  left: 50%;
  transform: translateX(-50%);
  top: 0;
  bottom: 0;
  margin: auto;
}
</style>